package com.ztgf.commodity.scheduled;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.commodity.models.bo.CommodityReleaseBO;
import com.ztgf.commodity.models.dto.CommodityCategoryDTO;
import com.ztgf.commodity.models.dto.CommodityComboRelationDTO;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.service.ICommodityCategoryService;
import com.ztgf.commodity.models.service.ICommodityComboRelationService;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.vo.CommodityCategoryTreeVO;
import com.ztgf.commodity.models.vo.CommodityEsVO;
import com.ztgf.commodity.models.vo.CommodityShopCategoryVO;
import com.ztgf.common.bo.HeadParamsBO;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.HttpUtils;
import com.ztgf.common.utils.JDAccessToken;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.search.models.dto.EsGoodsDTO;
import com.ztgf.search.models.service.SearchService;
import com.ztgf.sys.models.bo.SysLogSaveBO;
import com.ztgf.sys.models.service.ISysLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description ：
 * @Author ： 解风
 * @Date ： 2018/01/26 14:10
 */
//@Component
@Slf4j
public class ScheduledTimes {


    @DubboReference
    private ICommodityCategoryService commodityCategoryService;

    @DubboReference
    private ICommodityInfoService commodityInfoService;

    @DubboReference
    private ICommodityComboRelationService commodityComboRelationService;

    @Autowired
    private RedisUtil redisUtil;

    @DubboReference
    private ISysLogService sysLogService;

    @Value("${commodity.shopId}")
    private Long sid;

    @Value("${commodity.brandId}")
    private Long bid;

    @DubboReference
    private SearchService searchService;

    /**
     * 每10分钟更新佣金
     */
    @Scheduled(cron="0 0/10 * * * ?")
    public void executeCommissionUpdate() throws InterruptedException {
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<> ();
        wrapper.eq("effective_status", 1);//启动中的
        List<CommodityCategoryDTO> dtos = commodityCategoryService.selectList(wrapper);
        if(CustomizeUtil.listIsNotNull (dtos)){
            List<CommodityCategoryDTO> commodityCategoryDTOList = new ArrayList<>();
            for (CommodityCategoryDTO dto : dtos){
                if (dto.getEffectiveTime() != null){
                    Long now_m = System.currentTimeMillis(); //获取当前时间毫秒数
                    Long now_s = dto.getEffectiveTime().getTime(); //获取生效时间毫秒数
                    if (now_m > now_s){
                        //超过时间.设置数据
                        CommodityCategoryDTO commodityCategoryDTO = new CommodityCategoryDTO();
                        commodityCategoryDTO.setId(dto.getId());
                        commodityCategoryDTO.setDividendScale(dto.getFutureDividendScale());
                        commodityCategoryDTO.setEffectiveStatus(0);//0未启动，1启动中
                        commodityCategoryDTOList.add (commodityCategoryDTO);
                    }
                }
            }
            boolean falg = commodityCategoryService.updateDividendScaleByScheduled(commodityCategoryDTOList);

        }


        log.info("--------------定时任务：每10分钟更新佣金 ------------------");
    }

    @Scheduled(cron="0/5 * * * * ?")
    public void getToken() throws InterruptedException {
        Object objToken = redisUtil.get("token");
        log.info("----------获取Token-----------------------------"+objToken);
        if (null == objToken) {
            Map<String, String> tokenMap = JDAccessToken.getToken();
            if (null != tokenMap) {
                redisUtil.set("token", tokenMap.get("token").toString(), Long.parseLong(tokenMap.get("expires").toString()));
            }
        }
        objToken = redisUtil.get("token");
        //消费商品池
        consumerCommodityPool(objToken);
    }


    //消费商品池消息
    private void consumerCommodityPool(Object objToken) throws InterruptedException {
        log.info("----------商品池消息开始-----------------------------");
        if(null != objToken){
            //商品池新增删除
            JSONObject jsonObject = this.getJDMessage(objToken.toString(),"48");
            String resultCode  = jsonObject.getString("resultCode");
            if(resultCode.equals("0000")){
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject obj = jsonArray.getJSONObject(i).getJSONObject("result");
                    String pageNum = obj.getString("page_num");
                    //String id = obj.getString("id");
                    String id = jsonArray.getJSONObject(i).getString("id");
                    //state 1代表添加   2代表删除
                    String state = obj.getString("state");
                    if(state.equals("2")){
                        //删除
                        boolean b = deletJDCommodity("",pageNum);
                        deleteMessage(objToken.toString(),id);
                        saveSysLog(objToken.toString(),pageNum+":---删除商品池消息");
                        log.info("-------------删除商品池消息---------------:"+pageNum);
                    }else{
                        deleteMessage(objToken.toString(),id);
                        saveSysLog(objToken.toString(),pageNum+":---新增商品池消息");
                        log.info("-------------新增商品池消息---------------:"+pageNum);
                    }
                }
            }else if(!resultCode.equals("0010") && !resultCode.equals("0000")){
                saveSysLog(objToken.toString(),jsonObject.toJSONString());
            }

            //循环消费商品池
            if(resultCode.equals("0000")){
                consumerCommodityPool(objToken);
            }else{
                //单个消费商品
                //consumerCommodity(objToken);
                //批量消费商品
                consumerBatchCommodity(objToken);
            }
        }
        log.info("----------商品池定时结束-----------------------------");
    }


    //消费商品消息
    private void consumerCommodity(Object objToken) throws InterruptedException {
        log.info("----------商品消息开始-----------------------------");
        if(null != objToken){
            //商品池商品增加、删除
            JSONObject jsonObject = this.getJDMessage(objToken.toString(),"6");
            String resultCode  = jsonObject.getString("resultCode");
            if(resultCode.equals("0000")){
                //state 0代表删除  1代表新增
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject obj = jsonArray.getJSONObject(i).getJSONObject("result");
                    String state = obj.getString("state");
                    String skuId = obj.getString("skuId");
                    String pageNum = obj.getString("page_num");
                    String id = jsonArray.getJSONObject(i).getString("id");
                    //新增
                    if(state.equals("1")){
                        CommodityReleaseBO bo = getJDCommodity(objToken.toString(),skuId,null,pageNum);
                        if(null != bo && bo.getCategoryId() != 0 ){
                            Result<List<String>> result = saveCommodity(bo);
                            if(result.getCode() == 0){
                                deleteMessage(objToken.toString(),id);
                                saveSysLog(objToken.toString(),skuId+":---新增商品成功");
                            }
                        }else{
                            log.info("--------------commodity-------------商品不在商品池");
                            deleteMessage(objToken.toString(),id);
                        }
                    }else{
                        //删除
                        log.info("--------------commodity-------------删除商品："+skuId);
                        boolean b = deletJDCommodity(skuId,"");
                        if(b){
                            deleteMessage(objToken.toString(),id);
                            saveSysLog(objToken.toString(),skuId+":---删除成功");
                        }else{
                            deleteMessage(objToken.toString(),id);
                            saveSysLog(objToken.toString(),skuId+":---删除失败");
                        }
                    }
                }
            }else if(!resultCode.equals("0010") && !resultCode.equals("0000")){
                saveSysLog(objToken.toString(),jsonObject.toJSONString());
            }

            if(resultCode.equals("0000")){
                consumerCommodity(objToken);
            }else{
                consumerChangeCommodity(objToken);
            }
        }
        log.info("----------商品定时结束-----------------------------");
    }


    //批量消费商品消息
    @Transactional
    public void consumerBatchCommodity(Object objToken) throws InterruptedException {
        log.info("批量新增----------商品消息开始-----------------------------");
        if(null != objToken){
            //商品池商品增加、删除
            JSONObject jsonObject = this.getJDMessage(objToken.toString(),"6");
            String resultCode  = jsonObject.getString("resultCode");
            if(resultCode.equals("0000")){
                List<CommodityReleaseBO> commodityReleaseBOList = new ArrayList<>();
                //state 0代表删除  1代表新增
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject obj = jsonArray.getJSONObject(i).getJSONObject("result");
                    String state = obj.getString("state");
                    String skuId = obj.getString("skuId");
                    String pageNum = obj.getString("page_num");
                    String id = jsonArray.getJSONObject(i).getString("id");
                    //新增
                    if(state.equals("1")){
                        CommodityReleaseBO bo = getJDCommodity(objToken.toString(),skuId,null,pageNum);
                        bo.setParamValues(id);
                        commodityReleaseBOList.add(bo);
                    }else{
                        //删除
                        log.info("--------------commodity-------------删除商品："+skuId);
                        boolean b = deletJDCommodity(skuId,"");
                        if(b){
                            deleteMessage(objToken.toString(),id);
                            saveSysLog(objToken.toString(),skuId+":---删除成功");
                        }else{
                            deleteMessage(objToken.toString(),id);
                            saveSysLog(objToken.toString(),skuId+":---删除失败");
                        }
                    }
                }

                Map<String,List> map = commodityInfoService.getCommodityList(commodityReleaseBOList);
                List<CommodityInfoDTO> commodityInfoDTOList = map.get("commodityInfoDTOList");
                List<CommodityComboRelationDTO> commodityComboRelationDTOList = map.get("commodityComboRelationDTOList");

                if(null != commodityInfoDTOList && commodityInfoDTOList.size() > 0){
                    commodityInfoService.insertBatch(commodityInfoDTOList);
                }

                if(null != commodityComboRelationDTOList && commodityComboRelationDTOList.size() > 0){
                    commodityComboRelationService.insertBatch(commodityComboRelationDTOList);
                }

                for(CommodityReleaseBO commodityReleaseBO : commodityReleaseBOList){
                    deleteMessage(objToken.toString(),commodityReleaseBO.getParamValues());
                }

            }else if(!resultCode.equals("0010") && !resultCode.equals("0000")){
                saveSysLog(objToken.toString(),jsonObject.toJSONString());
            }

            if(resultCode.equals("0000")){
                consumerBatchCommodity(objToken);
            }else{
                consumerChangeCommodity(objToken);
            }
        }
        log.info("----------商品定时结束-----------------------------");
    }


    //变更商品消息
    private void consumerChangeCommodity(Object objToken) throws InterruptedException {
        log.info("----------变更商品消息开始-----------------------------");
        if(null != objToken){
            JSONObject jsonObject = this.getJDMessage(objToken.toString(),"16");
            String resultCode  = jsonObject.getString("resultCode");
            if(resultCode.equals("0000")){
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject obj = jsonArray.getJSONObject(i).getJSONObject("result");
                    String skuId = obj.getString("skuId");
                    String id = jsonArray.getJSONObject(i).getString("id");
                    log.info("----------变更消息对应skuid-----------------------------"+skuId);
                    //更新商品信息
                    Result<List<String>> result = updateJDGoods(objToken.toString(),skuId);
                    if(result.getCode() == 0){
                        deleteMessage(objToken.toString(),id);
                        saveSysLog(objToken.toString(),skuId+":---变更商品信息成功");
                    }else{
                        deleteMessage(objToken.toString(),id);
                        saveSysLog(objToken.toString(),skuId+":---变更商品信息失败");
                    }
                }
            }else if(!resultCode.equals("0010") && !resultCode.equals("0000")){
                saveSysLog(objToken.toString(),jsonObject.toJSONString());
            }

            if(resultCode.equals("0000")){
                consumerChangeCommodity(objToken);
            }else{
                consumerPutawayCommodity(objToken);
            }
        }
        log.info("----------变更商品定时结束-----------------------------");
    }

    //上下架商品消息
    private void consumerPutawayCommodity(Object objToken) throws InterruptedException {
        log.info("----------上下架商品消息开始-----------------------------");
        if(null != objToken){
            JSONObject jsonObject = this.getJDMessage(objToken.toString(),"4");
            String resultCode  = jsonObject.getString("resultCode");
            if(resultCode.equals("0000")){
                //state 0代表下架   1代表上架
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject obj = jsonArray.getJSONObject(i).getJSONObject("result");
                    String state = obj.getString("state");
                    String skuId = obj.getString("skuId");
                    String id = jsonArray.getJSONObject(i).getString("id");
                    if(!updateJDGoodsOutOfStock(Integer.parseInt(state),skuId)){
                        deleteMessage(objToken.toString(),id);
                        log.info("---------------上下架更新失败----------"+skuId);
                        saveSysLog(objToken.toString(),jsonObject.toJSONString()+":上下架更新失败");
                    }else{
                        deleteMessage(objToken.toString(),id);
                        saveSysLog(objToken.toString(),jsonObject.toJSONString()+":上下架更新成功");
                    }
                }
            }else if(!resultCode.equals("0010") && !resultCode.equals("0000")){
                saveSysLog(objToken.toString(),jsonObject.toJSONString());
            }

            if(resultCode.equals("0000")){
                consumerPutawayCommodity(objToken);
            }
        }
        log.info("----------上下架商品定时结束-----------------------------");
    }



    private JSONObject getJDMessage(String token,String type){
        Map param = new HashMap();
        param.put("token",token);
        param.put("type",type);
        //获取京东Message推送
        String str = HttpUtils.doPost("https://api-iop.jd.com/api/message/get",param);
        JSONObject jsonObject = JSONObject.parseObject(str);
        return jsonObject;
    }

    //更新上下架状态
    private boolean updateJDGoodsOutOfStock(Integer state,String skuId){
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_number",skuId);
        CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
        commodityInfoDTO.setIsPublish(state);
        boolean b = commodityInfoService.update(commodityInfoDTO,wrapper);
        if(b == true){
            if(state == 0){
                CommodityInfoDTO dto = commodityInfoService.selectOne(wrapper);
                searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
                dto.setIsSynEs(0);
                wrapper = new EntityWrapper();
                wrapper.eq("id",dto.getId());
                commodityInfoService.update(dto,wrapper);
                return true;
            }else{
                CommodityInfoDTO dto = commodityInfoService.selectOne(wrapper);
                CommodityEsVO goods = commodityInfoService.queryESGoodsById(dto.getId());
                List<EsGoodsDTO> esGoods = commodityInfoService.getEsGoods(goods);
                searchService.addGoods("index_goods_2020", "goods", 0, esGoods.size(), esGoods);
                return true;
            }
        }
        return false;
    }

    //更新商品信息
    private Result<List<String>> updateJDGoods(String token,String skuId){
        log.info("----------更新京东商品-----------------------------"+skuId);
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_number",skuId);
        CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectOne(wrapper);
        if(null != commodityInfoDTO){
            Wrapper<CommodityComboRelationDTO> wrapper2 = new EntityWrapper<>();
            wrapper2.eq("commodity_id",commodityInfoDTO.getId());
            CommodityComboRelationDTO commodityComboRelationDTO = commodityComboRelationService.selectOne(wrapper2);
            CommodityReleaseBO bo = getJDCommodity(token,skuId,commodityComboRelationDTO.getId(),"");
            bo.setId(commodityInfoDTO.getId());
            if(null != bo){
                Result<List<String>> result = commodityInfoService.update(bo);
                if(result.getCode() != 0){
                    log.info("更新商品信息----------------------------sku:"+skuId+"------------成功");
                    return result;
                }
            }
        }
        return new Result<>(CodeEnum.SUCCESS);
    }


    //删除消息
    private void deleteMessage(String token,String id){
        //删除消息
        Map map =  new HashMap();
        map.put("token",token);
        map.put("id",id);
        String str = HttpUtils.doPost(" https://api-iop.jd.com/api/message/del",map);
        JSONObject jsonObject = JSONObject.parseObject(str);
        String resultCode  = jsonObject.getString("resultCode");
        if(resultCode.equals("0000")){
            log.info("删除------------------------"+id+"--------------------成功");
        }else{
            saveSysLog(map.toString(),jsonObject.toJSONString());
        }
    }

    private void saveJDCommodity(String objToken,String pageNum,int pageSize,Map<String,String> skusMap){
        if(null != skusMap && skusMap.size() > 0){
            String skus = skusMap.get("skus");
            String offset = skusMap.get("offset");
            skus = skus.substring(1,skus.length()-1);
            //TODO获取商品详情信息
            String[] strs =  skus.split(",");
            for(String sku : strs){
                Map detailMap =  new HashMap();
                detailMap.put("token",objToken);
                detailMap.put("sku",sku);
                detailMap.put("queryExts","nintroduction,categoryAttrs,seoModel,paramDetailJson,taxInfo,wserve,color,sizeDesc");
                String str = HttpUtils.doPost("https://api-iop.jd.com/api/product/getDetail",detailMap);
                JSONObject jsonObject = JSONObject.parseObject(str);
                String resultCode  = jsonObject.getString("resultCode");
                if(resultCode.equals("0000")){
                    String brandName = jsonObject.getJSONObject("result").getString("brandName");
                    String imagePath = jsonObject.getJSONObject("result").getString("imagePath");
                    String taxInfo = jsonObject.getJSONObject("result").getString("taxInfo");
                    String param = jsonObject.getJSONObject("result").getString("param");
                    String name = jsonObject.getJSONObject("result").getString("name");
                    String introduction = jsonObject.getJSONObject("result").getString("introduction");
                    String state = jsonObject.getJSONObject("result").getString("state");
                    String wserve = jsonObject.getJSONObject("result").getString("wserve");
                    String wareQD = jsonObject.getJSONObject("result").getString("wareQD");
                    String jdsku = jsonObject.getJSONObject("result").getString("sku");
                    String categoryAttrs = jsonObject.getJSONObject("result").getString("categoryAttrs");
                    String saleUnit = jsonObject.getJSONObject("result").getString("saleUnit");
                    String seoModel = jsonObject.getJSONObject("result").getString("seoModel");
                    String length = jsonObject.getJSONObject("result").getString("length");
                    String width = jsonObject.getJSONObject("result").getString("width");
                    String height = jsonObject.getJSONObject("result").getString("height");
                    //查询类目id数据
                    Long categoryId = this.getJDCategory(objToken,jsonObject.getJSONObject("result").getString("category"));
                    //查询图片
                    Map<String,String> imageMap = this.getJDImage(objToken,jdsku);

                    //店铺ID
                    Long shopId = sid;
                    CommodityReleaseBO bo = new CommodityReleaseBO();
                    //店铺ID
                    bo.setShopId(shopId);
                    //品牌ID
                    bo.setBrandId(bid);
                    bo.setCategoryId(categoryId);
                    //商品编号
                    bo.setCommodityNumber(jdsku);
                    bo.setDescription(wareQD);
                    bo.setLogoUrl(imageMap.get("primaryPath"));
                    bo.setLogoUrls(imageMap.get("defalutPath"));
                    bo.setName(name);
                    bo.setSendDays(7);
                    bo.setType(0);
                    bo.setNotes(introduction);
                    bo.setIsInquiry(1);
                    bo.setWarrantyMonth(12);
                    bo.setAuditStatus(1);
                    bo.setIsPublish(1);
                    bo.setJdFlag(1);
                    bo.setJdPageNum(pageNum);
                    //发货地址id
                    bo.setSendAreaId(510106L);
                    bo.setSellerAddressId(621284652577062912L);

                    JSONArray array = new JSONArray();
                    JSONObject obj = new JSONObject();
                    obj.put("batchNumber","");
                    obj.put("chang",length);
                    obj.put("kuan",width);
                    obj.put("gao",height);
                    obj.put("comboName",name);
                    obj.put("commoditySize",length+"x"+width+"x"+height);
                    obj.put("commoditySizeUnit","0");
                    //商品单位(PCS)
                    obj.put("commodityUnit","431476233465888768");
                    //库存数量
                    obj.put("inventoryNumber","99");
                    //库存预警
                    obj.put("inventoryNumberWarning","2");
                    obj.put("setMeal",true);
                    array.add(obj);
                    bo.setCombos(array.toJSONString());

                    Wrapper wrapper = new EntityWrapper();
                    wrapper.eq("commodity_number",jdsku);
                    //查询商品是否已保存
                    CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectOne(wrapper);
                    if(null == commodityInfoDTO && categoryId != 0){
                        //保存商品信息
                        Result<List<String>> result = commodityInfoService.saveReleaseCommodity(bo);
                        if(result.getCode() != 0){
                            log.info("--------------save_commodity_info_result--------------"+result.getMsg());
                            saveSysLog(detailMap.toString(),jsonObject.toJSONString());
                        }
                    }

                }else{
                    saveSysLog(detailMap.toString(),jsonObject.toJSONString());
                }

            }
            Map<String,String> map = JDAccessToken.getJDsku(objToken,pageNum,pageSize,offset);
            if(null != map && map.size() > 0){
                this.saveJDCommodity(objToken,pageNum,pageSize,map);
            }
        }
    }

    private CommodityReleaseBO getJDCommodity(String objToken,String skuId,Long comboId,String pageNum){
        //TODO获取商品详情信息
        Map detailMap =  new HashMap();
        detailMap.put("token",objToken);
        detailMap.put("sku",skuId);
        detailMap.put("queryExts","nintroduction,categoryAttrs,seoModel,paramDetailJson,taxInfo,wserve,color,sizeDesc");
        String str = HttpUtils.doPost("https://api-iop.jd.com/api/product/getDetail",detailMap);
        JSONObject jsonObject = JSONObject.parseObject(str);
        String resultCode  = jsonObject.getString("resultCode");
        if(null != resultCode && resultCode.equals("0000")){
            String brandName = jsonObject.getJSONObject("result").getString("brandName");
            String imagePath = jsonObject.getJSONObject("result").getString("imagePath");
            String taxInfo = jsonObject.getJSONObject("result").getString("taxInfo");
            String param = jsonObject.getJSONObject("result").getString("param");
            String name = jsonObject.getJSONObject("result").getString("name");
            String introduction = jsonObject.getJSONObject("result").getString("introduction");
            String state = jsonObject.getJSONObject("result").getString("state");
            String wserve = jsonObject.getJSONObject("result").getString("wserve");
            String wareQD = jsonObject.getJSONObject("result").getString("wareQD");
            String jdsku = jsonObject.getJSONObject("result").getString("sku");
            String categoryAttrs = jsonObject.getJSONObject("result").getString("categoryAttrs");
            String saleUnit = jsonObject.getJSONObject("result").getString("saleUnit");
            String seoModel = jsonObject.getJSONObject("result").getString("seoModel");
            String length = jsonObject.getJSONObject("result").getString("length");
            String width = jsonObject.getJSONObject("result").getString("width");
            String height = jsonObject.getJSONObject("result").getString("height");
            //查询类目id数据
            Long categoryId = this.getJDCategory(objToken,jsonObject.getJSONObject("result").getString("category"));

            //查询图片
            Map<String,String> imageMap = this.getJDImage(objToken,jdsku);

            //店铺ID
            Long shopId = sid;
            CommodityReleaseBO bo = new CommodityReleaseBO();
            //店铺ID
            bo.setShopId(shopId);
            //品牌ID
            bo.setBrandId(bid);
            bo.setCategoryId(categoryId);
            //商品编号
            bo.setCommodityNumber(jdsku);
            bo.setDescription(wareQD);
            bo.setLogoUrl(imageMap.get("primaryPath"));
            bo.setLogoUrls(imageMap.get("defalutPath"));
            bo.setName(name);
            bo.setSendDays(7);
            bo.setType(0);
            bo.setNotes(introduction);
            bo.setIsInquiry(1);
            bo.setWarrantyMonth(12);
            bo.setAuditStatus(1);
            bo.setIsPublish(1);
            bo.setJdFlag(1);
            bo.setJdPageNum(pageNum);
            //发货地址id
            bo.setSendAreaId(510106L);
            bo.setSellerAddressId(621284652577062912L);

            JSONArray array = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("batchNumber","");
            obj.put("chang",length);
            obj.put("kuan",width);
            obj.put("gao",height);
            obj.put("comboName",name);
            obj.put("commoditySize",length+"x"+width+"x"+height);
            obj.put("commoditySizeUnit","0");
            //修改的时候需要传id
            if(null != comboId){
                obj.put("id",comboId);
            }
            //商品单位(PCS)
            obj.put("commodityUnit","431476233465888768");
            //库存数量
            obj.put("inventoryNumber","99");
            //库存预警
            obj.put("inventoryNumberWarning","2");
            obj.put("setMeal",true);
            array.add(obj);
            bo.setCombos(array.toJSONString());

            return bo;
        }else{
            saveSysLog(detailMap.toString(),jsonObject.toJSONString());
            log.info("--------------result---------------"+jsonObject.toJSONString());
        }

        return null;
    }

    private void saveSysLog(String params,String result){
        SysLogSaveBO sysLog = new SysLogSaveBO();
        HeadParamsBO headParamsBO = CommonParameter.getHeadParamsBO();
        // 获取IP
        sysLog.setIp(headParamsBO.getClientIp());
        sysLog.setUri(headParamsBO.getRequestURI());
        // 根据系统需求自定义
        sysLog.setParams(params);
        sysLog.setUsername("jd");
        sysLog.setActionName(result);
        sysLog.setHttpMethod(headParamsBO.getMethod());
        sysLogService.add(sysLog);
    }

    private Result<List<String>> saveCommodity(CommodityReleaseBO bo){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("commodity_number",bo.getCommodityNumber());
        //查询商品是否已保存
        CommodityInfoDTO commodityInfoDTO = commodityInfoService.selectOne(wrapper);
        if(null == commodityInfoDTO){
            //保存商品信息
            Result<List<String>> result = commodityInfoService.saveReleaseCommodity(bo);
            if(result.getCode() != 0){
                log.info("--------------save_commodity_info_result--------------"+result.getMsg());
                saveSysLog(bo.getCommodityNumber(),result.getMsg());
                return result;
            }
        }
        return new Result<>(CodeEnum.SUCCESS);
    }

    private boolean deletJDCommodity(String skuId,String pageNum){
        Wrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
        if(StringUtils.isNotEmpty(skuId)){
            wrapper.eq("commodity_number",skuId);
        }
        if(StringUtils.isNotEmpty(pageNum)){
            wrapper.eq("jd_page_num",pageNum);
        }
        CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
        commodityInfoDTO.setIsRemove(1);
        commodityInfoDTO.setStatus(1);
        boolean b = commodityInfoService.update(commodityInfoDTO,wrapper);
        if(b){
            CommodityInfoDTO dto = commodityInfoService.selectOne(wrapper);
            searchService.deleteData("index_goods_2020", "goods", dto.getId().toString());
            dto.setIsSynEs(0);
            wrapper = new EntityWrapper();
            wrapper.eq("id",dto.getId());
            commodityInfoService.update(dto,wrapper);
            return true;
        }
        return true;
    }

    private Map<String,String> getJDImage(String token,String sku){
        Map<String,String> resultMap = new HashMap();
        StringBuffer sb = new StringBuffer();
        Map map =  new HashMap();
        map.put("token",token);
        map.put("sku",sku);
        String str = HttpUtils.doPost("https://api-iop.jd.com/api/product/skuImage",map);
        JSONObject jsonObject = JSONObject.parseObject(str);
        String resultCode  = jsonObject.getString("resultCode");
        if(resultCode.equals("0000")){
            JSONArray array = jsonObject.getJSONObject("result").getJSONArray(sku);
            if(null != array && array.size() > 0){
                int count = 0;
                for(int i=0;i<array.size();i++){
                    String isPrimary = array.getJSONObject(i).getString("isPrimary");
                    String imagePath = array.getJSONObject(i).getString("path");
                    //主图
                    if(isPrimary.equals("1")){
                        resultMap.put("primaryPath","jdzt-"+imagePath);
                    }else{
                        if(count <= 3){
                            sb.append("jdzt-"+imagePath);
                        }
                        if(count < 3 && i != array.size() - 1){
                            sb.append(",");
                        }
                        count ++;
                    }
                }
                resultMap.put("defalutPath",sb.toString());
            }
        }

        return resultMap;
    }


    private Long getJDCategory(String token,String cids){
        if(StringUtils.isNotEmpty(cids) && cids.contains(";")){
            String[] cidArr = cids.split(";");

            //TODO 中铁店铺ID
            List<CommodityShopCategoryVO> shopCategoryVOList = commodityCategoryService.queryShopCategory(sid,cidArr[cidArr.length-1]);
            if(null != shopCategoryVOList && shopCategoryVOList.size() > 0){
                return shopCategoryVOList.get(0).getCategoryId();
            }else{
                saveSysLog(token,cids+":----类目查询失败");
            }
            return 0L;
        }
        return 0L;
    }


}
